package com.jsmile.cloud.tradecenter.express.kit;

import org.apache.commons.lang3.exception.ExceptionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jsmile.cloud.tradecenter.api.enums.TradeCodeEnum;
import com.jsmile.cloud.tradecenter.api.exception.TradeException;
import com.jsmile.cloud.tradecenter.express.repo.ExpressCompanySearchRepository;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.contant.CompanyConstant;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.utils.SignUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Kuaidi100Kit {

    public static void main(String[] args) throws Exception {
        kuadi100Query("13135676935", CompanyConstant.YD, "4311844390564");
    }

    /**
     * 快递100物流查询
     *
     * @param phone
     *            手机号码
     * @param companyCode
     *            公司编号
     * @param expressNo
     *            快递编码
     */
    public static JSONObject kuadi100Query(String phone, String companyCode, String expressNo) {
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        queryTrackParam.setCom(companyCode);
        queryTrackParam.setNum(expressNo);
        queryTrackParam.setPhone(phone);
        String param = new Gson().toJson(queryTrackParam);
        queryTrackReq.setParam(param);
        queryTrackReq.setCustomer("506E2F52885D9AC669B77D2CFBDAB5E7");
        queryTrackReq.setSign(SignUtils.querySign(param, "bOpXRWBh7822", "506E2F52885D9AC669B77D2CFBDAB5E7"));
        IBaseClient baseClient = new QueryTrack();
        try {
            HttpResult httpResult = baseClient.execute(queryTrackReq);
            log.info("物流查询结果：{}", JSON.toJSONString(httpResult));
            if (200 == httpResult.getStatus()) {
                JSONObject json = JSON.parseObject(httpResult.getBody());
                json.put("companyName", ExpressCompanySearchRepository.expressMap.get(companyCode).getCompanyName());
                json.put("companyCode", companyCode);
                json.put("expressNo", expressNo);
                return json;
            }
        } catch (Exception e) {
            log.info("物流查询失败：{}", ExceptionUtils.getStackTrace(e));
            throw new TradeException(TradeCodeEnum.EXPRESS_NOT_EXISTS);
        }
        throw new TradeException(TradeCodeEnum.EXPRESS_NOT_EXISTS);
    }
}
